/**
 * 
 */
package com.bestbuy.controller;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.dom4j.rule.Mode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.FacebookLink;
import org.springframework.social.facebook.api.Post;
import org.springframework.social.facebook.api.impl.FacebookTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.bestbuy.pojo.Account;
import com.bestbuy.pojo.Catalog;
import com.bestbuy.pojo.Comment;
import com.bestbuy.pojo.CommentInfo;
import com.bestbuy.pojo.FileUploadItem;
import com.bestbuy.pojo.Product;
import com.bestbuy.service.AccountService;
import com.bestbuy.service.CatalogService;
import com.bestbuy.service.CommentService;
import com.bestbuy.service.ProductService;

/**
 * @author ThanhNgo
 * 
 */
@Controller
public class ProductController {

	@Autowired
	private CatalogService catalogService;
	@Autowired
	private ProductService productService;
	@Autowired
	private CommentService commentService;
	@Autowired
	private AccountService accountService;

	@RequestMapping(value = { "/productdetail.do" }, method = RequestMethod.GET)
	public String getProductDetail(
			@RequestParam(value = "idproduct") String idProduct, Model model) {
		//List<Catalog> listCatalog = catalogService.getListCatalog();
		List<Catalog> listCatalog = catalogService.getListCatalogByDeleted("0");
		model.addAttribute("catalogs", listCatalog);
		//List<Product> listProduct = productService.Search("", "0", "1");
		List<Product> listProduct = productService.Search("", "0", "1", "0");
		model.addAttribute("products", listProduct);
		Product product = productService.getProduct(idProduct);
		product.getProductdetail().setView(product.getProductdetail().getView() + 1);
		productService.updateProduct(product);
		model.addAttribute("product", product);
		List<Comment> listComment = commentService.getListComment(idProduct);
		model.addAttribute("comments", listComment);
		model.addAttribute("Page", "ProductDetail");
		return "Main";
	}
	
	
	// comment
	@RequestMapping(value = { "/AjaxComment.do" }, method = RequestMethod.POST)
	@ResponseBody
	public CommentInfo AddComment(@ModelAttribute(value="commentInfo") CommentInfo commentInfo, BindingResult result, HttpSession session)
	{
		String returnText;
        if(!result.hasErrors())
        {
	
			String username = commentInfo.getUsername();
	    	Account account = accountService.GetAccount(username);
	    	Product product = productService.getProduct(commentInfo.getIdproduct());
	    	Comment comment = new Comment();
	    	DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
	    	//get current date time with Date()
	        Date date = new Date();
	    	comment.setDatecreated(dateFormat.format(date));
			comment.setAccount(account);
			comment.setText(commentInfo.getMessage());
			comment.setProduct(product);
			commentService.addComment(comment);
			// luu thong tin json de tra ve
			commentInfo.setDateCreated(dateFormat.format(date));
			// post comment len facebook
			String accessToken = (String)session.getAttribute("token");
			FacebookTemplate facebook = new FacebookTemplate(accessToken);
			String link = facebook.userOperations().getUserProfile().getLink();
			commentInfo.setDateCreated(dateFormat.format(date));
			commentInfo.setLinkFacebook(account.getAccountInfo().getLinkFacebook());
			return commentInfo;
        }
        else
        {
            return null;
        }
	}
	
	
	private String uploadFolderPath;
	ServletConfig config;

	public String getUploadFolderPath() {
		return uploadFolderPath;
	}

	public void setUploadFolderPath(String uploadFolderPath) {
		this.uploadFolderPath = uploadFolderPath;
	}
	
	
	
	
	
	
	
//	@RequestMapping(method = RequestMethod.GET)
//	public String getUploadForm(Model model) {
//		model.addAttribute(new FileUploadItem());
//		return "/uploadfile";
//	}
//
//	@RequestMapping(method = RequestMethod.POST)
//	public String create(FileUploadItem uploadItem, HttpServletRequest request,
//			HttpServletResponse response, Object command, BindException errors,
//			HttpSession session) {
//		try {
//
//			MultipartFile filea = uploadItem.getFileData();
//
//			InputStream inputStream = null;
//			OutputStream outputStream = null;
//			if (filea.getSize() > 0) {
//				inputStream = filea.getInputStream();
//				// File realUpload = new File("C:/");
//				outputStream = new FileOutputStream("C:\\test111\\"
//						+ filea.getOriginalFilename());
//				System.out.println("====22=========");
//				System.out.println(filea.getOriginalFilename());
//				System.out.println("=============");
//				int readBytes = 0;
//				byte[] buffer = new byte[8192];
//				while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
//					System.out.println("===ddd=======");
//					outputStream.write(buffer, 0, readBytes);
//				}
//				outputStream.close();
//				inputStream.close();
//				session.setAttribute("success", "File Uploaded Successfully");
//				session.setAttribute("uploadFile",
//						"C:\\test111\\" + filea.getOriginalFilename());
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return "redirect:/forms/uploadfileindex";
//	}
}
